package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.ElementAbstractUrl;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class HeiLongJiangService implements CrawlerScript {


    @Autowired
    private SaveDataUtil saveDataUtil;

    @Autowired
    private ChromeBrowser chromeBrowser;

    private static final Logger log = LoggerFactory.getLogger(HeiLongJiangService.class);
    private static final String province = "黑龙江";


    public void start() {

        ChromeDriver driver = chromeBrowser.getChromeDriver();
        try {
            driver.get("http://1.189.191.146:8000/eMonPubHLJ/Default.aspx");//打开网页
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            partClickNext(driver);
        } catch (Exception e) {
            log.error("{}--网页打开失败--{}", driver.getCurrentUrl(), e.getMessage());
        } finally {
            driver.quit();
            log.info("数据爬取结束");
        }

    }

    private void partClickNext(ChromeDriver driver) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        Elements allElements = parse.getAllElements();
        Elements elementsCity = allElements.select("#Map > area");
        List<String> urlList = new ArrayList<>();

        for (Element e : elementsCity) {
            String url = "http://1.189.191.146:8000/eMonPubHLJ/" + e.attr("href");
            urlList.add(url);
        }

        for (String url : urlList) {
            try {
                driver.get(url);
            } catch (Exception e) {
                log.error(url, e.getMessage());
                continue;
            }
            String htmlTmp = driver.findElementByTagName("html").getAttribute("outerHTML");
            Document parseTmp = Jsoup.parse(htmlTmp, driver.getCurrentUrl());
            Elements allElementsTmp = parseTmp.getAllElements();
            Elements elementsUrl = allElementsTmp.select("#ctl00_ctl00_cphMain_cphMainPage_TreeView1n0Nodes").get(0).getElementsByAttribute("target");

            List<String> urlCompanyList = ElementAbstractUrl.links(elementsUrl);
            for (int i = 0; i < elementsUrl.size(); i++) {
                List<MonitorData> monitorDataList = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                try {
                    driver.get(urlCompanyList.get(i));
                    String html = driver.findElementByTagName("html").getAttribute("outerHTML");
                    Document parseNew = Jsoup.parse(html, driver.getCurrentUrl());
                    Elements allElementsNew = parseNew.getAllElements();
                    jsonObject.put("entName", allElementsNew.select("#ctl00_ctl00_cphMain_cphMainPage_lblQYname").text());
                    jsonObject.put("address", allElementsNew.select("#ctl00_ctl00_cphMain_cphMainPage_lblAddress").text());

                    jsonObject.put("industry", allElementsNew.select("#ctl00_ctl00_cphMain_cphMainPage_lblHY").text());
                    jsonObject.put("type", allElementsNew.select("#ctl00_ctl00_cphMain_cphMainPage_lblType").text());
                    partBodyClickNext(driver, null, jsonObject, monitorDataList);
                } catch (Exception e) {
                    log.error(e.getMessage());
                    continue;
                }
                saveDataUtil.saveTag(monitorDataList, province);
            }

        }

    }


    private void partBodyClickNext(ChromeDriver driver, String html, JSONObject jsonObject, List<MonitorData> monitorDataList) {
        String htmlCompany = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parseCompany = Jsoup.parse(htmlCompany, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlCompany)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlCompany;
        Elements allElementsCompany = parseCompany.getAllElements();

        Elements elements = allElementsCompany.select("#ctl00_ctl00_cphMain_cphMainPage_UCDataSearch_gvHistoryData > tbody tr:nth-child(n+2)");
        if (!elements.text().equals("企业在当前查询条件下暂无数据，请更换查询条件")) {
            for (Element element : elements) {
                MonitorData monitorData = new MonitorData();
                if (!element.getElementsByTag("td").isEmpty() && !element.equals(elements.last())) {
                    monitorData.setProvince(province);
                    monitorData.setId(UUID.randomUUID().toString());
                    monitorData.setCompanyName(jsonObject.getString("entName"));
                    monitorData.setIndustry(jsonObject.getString("industry"));
                    monitorData.setAddress(jsonObject.getString("address"));
                    monitorData.setPollutionType(jsonObject.getString("type"));

                    monitorData.setMonitorPoint(element.getElementsByTag("td").get(0).text());
                    monitorData.setMonitorType(element.getElementsByTag("td").get(1).text());
                    monitorData.setMonitorTime(element.getElementsByTag("td").get(2).text());
                    monitorData.setMonitorInfo(element.getElementsByTag("td").get(3).text());

                    monitorData.setMonitorValue(element.getElementsByTag("td").get(5).text());
                    monitorData.setMonitorStandardValue(element.getElementsByTag("td").get(7).text());
                    monitorData.setOverproof(element.getElementsByTag("td").get(8).text());
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    monitorDataList.add(monitorData);

                }
            }
            log.info("当前页--{}", driver.getCurrentUrl());
            try {
                Thread.sleep(1000);
                WebElement webElement = driver.findElementByXPath("//*[@id='ctl00_ctl00_cphMain_cphMainPage_UCDataSearch_gvHistoryData_ctl23_lbnNext']");
                webElement.click();
                partBodyClickNext(driver, html, jsonObject, monitorDataList);
            } catch (Exception e) {
                log.error("点击下一页出错--{}", e.getMessage());
                return;
            }

        }

    }
}
